package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.api.RequestUtils;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.dialog.AuthCodeCharacterDialog;
import com.cardbaobao.cardbabyclient.ui.dialog.AuthCodeImageDialog;
import com.cardbaobao.cardbabyclient.model.MemberInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.SoftKeyboardUtils;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 10:35.
 * 运营商授权
 */
public class OperatorAuthActivity extends BaseActivity {
    private static final String TIPS =
            "此次请求预计耗时"+ (RequestUtils.READ_TIME_OUT_LONG/1000)+"秒\n请耐心等待";
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.et_account)
    EditText etAccount;

    @BindView(R.id.et_pwd)
    EditText etPwd;

    @BindView(R.id.bt_next_step)
    Button btNextStep;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mCurrentPageId=Self.Page.app_operator_auth_page;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_operator;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (memberInfo == null) {
            loadRealNameInfo(false);
        }
        UmengEventUtils.pageEvent(mContext, getString(R.string.event_0x03b));
        GoogleAnalyticsUtil.setScreenName(Google.OPERATOR_AUTH);
    }

    @OnClick({R.id.tv_agreement,R.id.bt_next_step})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_agreement:
                initIntent();
                SelfUtils.buriedClickData(Self.Action.app_click_operator_auth_agreement,
                        Self.Action.app_click_operator_auth_agreement_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);
                mIntent.setClass(mContext, AgreementWebViewActivity.class);
                mIntent.putExtra("title", "运营商授权协议");
                mIntent.putExtra("webUrl", URLUtil.DATA_PARSER_AGREEMENT);
                mIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                mIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I,17);
                startActivity(mIntent);
                break;
            case R.id.bt_next_step:
                SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
                if (btNextStep.getText().toString().trim().equals("下一步")) {
                    if (checkAccount() && checkPwd()) {
                        SelfUtils.buriedClickData(Self.Action.app_click_operator_auth,
                                Self.Action.app_click_operator_auth_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                mPrePageId);
                        GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_SERVICE, Google.ACTION_OPERATOR_AUTH);
                        if (memberInfo != null) {
                            createTask();
                        } else {
                            loadRealNameInfo(true);
                        }
                    }
                } else {
                    finish();
                }
                break;
        }
    }

    @OnCheckedChanged(R.id.cb_agreement)
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.getId() == R.id.cb_agreement && isChecked) {
            btNextStep.setEnabled(true);
        } else {
            btNextStep.setEnabled(false);
        }
    }

    private boolean checkAccount() {
        String phone = etAccount.getText().toString().trim();
        if (phone.length() == 11 && RegularUtil.isPhoneNumber(phone)) {
            return true;
        } else {
            ToastUtil.showToast("请输入正确的手机号码");
            return false;
        }
    }

    private boolean checkPwd() {
        String pwd = etPwd.getText().toString().trim();
        if (pwd.length() >= 6) {
            return true;
        } else {
            ToastUtil.showToast("密码格式错误");
            return false;
        }
    }

    private MemberInfo memberInfo;

    //获取实名认证信息
    private void loadRealNameInfo(final boolean createTask) {
        if (createTask) {
            showProgressDialog(false);
        }
        Observable<String> observable=
                Api.getMemberInfo(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
                if (createTask) {
                    dismissProgressDialog();
                }
            }

            @Override
            public void onNext(String s) {
                JSONObject json=JSON.parseObject(s);
                if(json!=null){
                    JSONObject object=json.getJSONObject("data");
                    if(object!=null){
                        memberInfo=JSON.parseObject(object.getString("MemberInfo"),MemberInfo.class);
                        if(createTask){
                            createTask();
                        }else{
                            dismissProgressDialog();
                        }
                    }else{
                        dismissProgressDialog();
                    }
                }else{
                    dismissProgressDialog();
                }
            }
        });
    }

    //输入图片验证码弹框
    private AuthCodeImageDialog authCodeImageDialog;

    private void showAuthImageDialog(Bitmap bitmap) {
        if (authCodeImageDialog == null) {
            authCodeImageDialog = new AuthCodeImageDialog(mContext);
            authCodeImageDialog.setButtonClickedListener(new AuthCodeImageDialog.OnAuthCodeButtonClicked() {
                @Override
                public void onRefreshButtonClicked() {
                    refreshImageAuthCode(taskId);
                }

                @Override
                public void onCommitButtonClicked(String authCode) {
                    authCodeImageDialog.dismiss();
                    auth(taskId, null, authCode);
                }
            });
            authCodeImageDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    authCodeImageDialog.callSoftKeyBoard();
                }
            });
        }
        authCodeImageDialog.clearText();
        authCodeImageDialog.setAuthImage(bitmap);
        if (!authCodeImageDialog.isShowing()) {
            authCodeImageDialog.show();
        }
    }

    //输入短信验证码弹框
    private AuthCodeCharacterDialog authCodeCharacterDialog;

    private void showAuthCharacterDialog() {
        if (authCodeCharacterDialog == null) {
            authCodeCharacterDialog = new AuthCodeCharacterDialog(mContext);
            authCodeCharacterDialog.setButtonClickedListener(new AuthCodeCharacterDialog.OnAuthCodeButtonClicked() {
                @Override
                public void onCommitButtonClicked(String authCode) {
                    authCodeCharacterDialog.dismiss();
                    auth(taskId, authCode, null);
                }
            });
            authCodeCharacterDialog.setOnShowListener(new DialogInterface.OnShowListener() {
                @Override
                public void onShow(DialogInterface dialog) {
                    authCodeCharacterDialog.callSoftKeyBoard();
                }
            });
        }
        authCodeCharacterDialog.clearText();
        if (!authCodeCharacterDialog.isShowing()) {
            authCodeCharacterDialog.show();
        }
    }

    private void dismissAuthDialog() {
        SoftKeyboardUtils.hideSoftKeyboard(getCurrentFocus());
        if (null != authCodeImageDialog && authCodeImageDialog.isShowing()) {
            authCodeImageDialog.dismiss();
        }
        if (null != authCodeCharacterDialog && authCodeCharacterDialog.isShowing()) {
            authCodeCharacterDialog.dismiss();
        }
    }

    private String taskId;

    private void createTask() {
        showProgressDialog(false, TIPS);
        Map<String,Object> params = new HashMap<>();
        final String mobile = etAccount.getText().toString().trim();
        params.put("user_name", mobile);
        params.put("user_pass", etPwd.getText().toString().trim());
        params.put("user_id", mApplication.getUser().getID());
        params.put("identity_code", memberInfo.getIDCardNo());
        params.put("user_mobile", mobile);
        params.put("real_name", memberInfo.getTrueName());
        Observable<String> observable=Api.yysCreateTask(params);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                JSONObject json=JSON.parseObject(s);
                taskId = json.getString("task_id");
                int code = json.getIntValue("code");
                switch (code) {
                    case 0:
                    case 1:
                        auth(taskId, null, null);
                        break;
                    case 300:
                        //输入图片验证码
                        dismissProgressDialog();
                        dismissAuthDialog();
                        byte[] bytes = Base64.decode(json.getString("auth_code"), Base64.DEFAULT);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        showAuthImageDialog(bitmap);
                        break;
                    case 301:
                        //输入短信验证码
                        dismissProgressDialog();
                        dismissAuthDialog();
                        showAuthCharacterDialog();
                        break;
                    default:
                        //失败
                        dismissProgressDialog();
                        ToastUtil.showToast(json.getString("message"));
                        break;
                }
            }
        });
    }

    /**
     * 用户输入验证码，开始授权
     *
     * @param taskId    运营商信息爬取任务id
     * @param smsCode   短信验证码内容
     * @param imageCode 图片验证码内容
     */
    private void auth(String taskId, String smsCode, String imageCode) {
        showProgressDialog(false, TIPS);
        Observable<String> observable=Api.yysAuth(taskId,smsCode,imageCode);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
                dismissProgressDialog();
                dismissAuthDialog();
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                switch (code) {
                    case 0:
                    case 1:
                        //0正在授权 1授权成功
                        dismissAuthDialog();
                        ToastUtil.showToast(json.getString("message"));
                        btNextStep.setText("返回");
                        break;
                    case 300:
                        //输入图片验证码
                        byte[] bytes = Base64.decode(json.getString("auth_code"), Base64.DEFAULT);
                        Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                        showAuthImageDialog(bitmap);
                        break;
                    case 301:
                        //输入短信验证码
                        showAuthCharacterDialog();
                        break;
                    default:
                        //失败
                        ToastUtil.showToast(json.getString("message"));
                        break;
                }
            }
        });
    }

    /**
     * 刷新图片验证码
     *
     * @param taskId 运营商爬取信息任务id
     */
    private void refreshImageAuthCode(String taskId) {
        showProgressDialog(false);
        Observable<String> observable=Api.yysRefreshAuthCode(taskId);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                int code = json.getIntValue("code");
                switch (code) {
                    case 101:
                        //请求图片验证码成功
                        byte[] bytes = Base64.decode(json.getJSONObject("data").getString("auth_code"),
                                Base64.DEFAULT);
                        showAuthImageDialog(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
                        break;
                    case 104:
                        //请求图片验证码失败
                        ToastUtil.showToast(json.getString("message"));
                        break;
                    case 127:
                        //请求验证码超过重试次数限制
                        ToastUtil.showToast(json.getString("message"));
                        break;
                }
            }
        });
    }
}
